<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.*" %>
<%@ page import="bean.User" %>
<%@ page import="bean.Category" %>
<%@ page import="bean.SubCategory" %>
<%@ page import="bean.Television" %>
<!DOCTYPE html>
<html>
<head>
    <title>电视机分类展示</title>
    <link rel="stylesheet" type="text/css" href="static/css/categories.css">
    <script src="static/js/jquery-1.7.2.js"></script>
    <style>
        .products {
            margin: 0;
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 50px 30px;
            padding: 10px;
            width: 100%;
            box-sizing: border-box;
        }
        
        .product {
            background: white;
            border-radius: 12px;
            box-shadow: 0 3px 10px rgba(0,0,0,0.1);
            padding: 20px;
            transition: transform 0.2s;
            display: flex;
            flex-direction: column;
            height: 100%;
            margin: 0;
        }
        
        .product:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.15);
        }
        
        .product img {
            width: 100%;
            max-width: 100%;
            height: 180px;
            object-fit: contain;
            margin-bottom: 15px;
            background: #f8f8f8;
            padding: 0;
            border-radius: 8px;
            box-sizing: border-box;
            align-self: center;
        }
        
        .product h3 {
            font-size: 1.2em;
            margin: 10px 0;
            color: #333;
        }
        
        .product .price {
            font-size: 1.3em;
            color: #e53935;
            font-weight: bold;
            margin: 10px 0;
        }
        
        .product p {
            color: #666;
            margin: 5px 0;
            line-height: 1.4;
        }

        @media (max-width: 1200px) {
            .products {
                grid-template-columns: repeat(3, 1fr);
            }
        }

        @media (max-width: 900px) {
            .products {
                grid-template-columns: repeat(2, 1fr);
            }
        }

        @media (max-width: 600px) {
            .products {
                grid-template-columns: repeat(1, 1fr);
            }
        }

        .top {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 20px;
            background: #fff;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .top-actions {
            display: flex;
            align-items: center;
            gap: 20px;
        }
        
        .add-product-btn {
            display: inline-block;
            padding: 8px 16px;
            background-color: #4CAF50;
            color: white;
            text-decoration: none;
            border-radius: 4px;
            transition: background-color 0.3s;
        }
        
        .add-product-btn:hover {
            background-color: #45a049;
        }
        
        .information {
            display: flex;
            align-items: center;
        }
        
        #infor-img {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            margin-left: 10px;
            cursor: pointer;
        }
        
        .dropdown-content {
            display: none;
            position: absolute;
            right: 0;
            background-color: #f9f9f9;
            min-width: 160px;
            box-shadow: 0 8px 16px rgba(0,0,0,0.2);
            z-index: 1;
            border-radius: 4px;
        }
        
        .dropdown-content a {
            color: black;
            padding: 12px 16px;
            text-decoration: none;
            display: block;
        }
        
        .dropdown-content a:hover {
            background-color: #f1f1f1;
        }
        
        .information:hover .dropdown-content {
            display: block;
        }
        
        /* 修改图片按钮样式 */
        .change-image-btn {
            display: none;
            position: absolute;
            top: 10px;
            right: 10px;
            background: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 5px 10px;
            border-radius: 4px;
            text-decoration: none;
            font-size: 12px;
        }
        
        .product:hover .change-image-btn {
            display: block;
        }
        
        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }
        
        .modal-content {
            background-color: #fefefe;
            margin: 15% auto;
            padding: 20px;
            border-radius: 5px;
            width: 300px;
            position: relative;
        }
        
        .close {
            position: absolute;
            right: 10px;
            top: 5px;
            font-size: 20px;
            cursor: pointer;
        }
        
        #updateImageForm {
            margin-top: 20px;
        }
        
        #updateImageForm button {
            margin-top: 10px;
            padding: 5px 15px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
    </style>
    <script>
       $(function () {
            // 在页面加载时，保存所有分类的原始数据
            const originalButtons = new Map();
            $('.category').each(function() {
                const $category = $(this);
                const $actions = $category.find('.actions');
                // 保存原始的HTML内容
                originalButtons.set($category.index(), $actions.html());
            });

            // 统一的取消删除模式函数
            function cancelDeleteMode($category) {
                const $deleteIcons = $category ? $category.find('.delete-small-icon') : $('.category.delete-mode .delete-small-icon');
                const $categories = $category ? $category : $('.category');
                const $deleteButtons = $category ? $category.find('.actions a.delete') : $('.actions a.delete');

                $deleteIcons.animate({
                    opacity: 0
                }, 300, function() {
                    $categories.removeClass('delete-mode');
                    $deleteButtons.text('删除');
                    $(this).css('display', 'none');
                });
            }

            // 修改恢复原始按钮函数
            function restoreOriginalButtons($actions) {
                const $category = $actions.closest('.category');
                const originalHtml = originalButtons.get($category.index());
                
                if (originalHtml) {
                    $actions.fadeOut(200, function() {
                        // 恢复原始的HTML内容
                        $(this).html(originalHtml).fadeIn(200, function() {
                            // 重新绑定事件
                            bindEvents($actions);
                        });
                    });
                }
            }

            // 统一的事件绑定函数
            function bindEvents($container) {
                $container.find('a.delete').off('click').on('click', handleDeleteClick);
                $container.find('a.edit').off('click').on('click', handleEditClick);
            }

            // 删除按钮的事件处理函数
            function handleDeleteClick(e) {
                e.preventDefault();
                const $category = $(this).closest('.category');
                const categoryId = $(this).attr('data-category-id');
                const $deleteIcons = $category.find('.delete-small-icon');

                // 重置其他分类
                $('.category').not($category).removeClass('delete-mode');
                $('.actions a.delete').not(this).text('删除');

                if ($(this).text() === '删除') {
                    // 进入删除模式
                    $(this).text('取消删除');
                    $category.addClass('delete-mode');
                    $deleteIcons.css({
                        display: 'inline',
                        opacity: 0
                    }).animate({
                        opacity: 1
                    }, 300);
                } else {
                    // 取消删除模式
                    cancelDeleteMode($category);
                }
            }

            // 编辑按钮的事件处理函数
            function handleEditClick(e) {
                e.preventDefault();
                const $category = $(this).closest('.category');
                const categoryId = $(this).attr('data-id');
                // 添加调试日志
                console.log('编辑按钮元素:', this);
                console.log('获取到的categoryId:', categoryId);

                const $actions = $category.find('.actions');

                // 如果已经在编辑模式，则不做任何操作
                if ($actions.find('.cancel-edit').length) {
                    return;
                }

                // 重置其他分类的编辑状态
                $('.category').not($category).find('.actions').each(function() {
                    restoreOriginalButtons($(this));
                });
                // 切换到编辑模式，使用获取到的categoryId
                $actions.fadeOut(200, function() {
                    const html =
                        '<a href="category?action=showAddForm&categoryId=' + categoryId + '" class="add-category">新增小分类</a> |' +
                        '<a href="editCategory?action=showEditForm&categoryId=' + categoryId + '" class="modify-category">修改大分类</a> |' +
                        '<a href="editSubCategory?action=showEditForm&categoryId=' + categoryId + '" class="modify-subcategory">修改小分类</a> |' +
                        '<a href="television?action=showAddForm&categoryId=' + categoryId + '" class="add-television">新增商品</a> |' +
                        '<a href="#" class="cancel-edit">取消编辑</a>';
                    $(this).html(html).fadeIn(200);

                    // 绑定取消编辑事件
                    $(this).find('.cancel-edit').on('click', function(e) {
                        e.preventDefault();
                        restoreOriginalButtons($actions);
                    });
                });
            }

            // 初始绑定
            bindEvents($('.actions'));

            // 修改取消编辑的处理代码
            $(document).on('click', '.actions a.cancel-edit', function(e) {
                e.preventDefault();
                e.stopPropagation();
                const $actions = $(this).closest('.actions');
                restoreOriginalButtons($actions);
            });

            // 修改点击其他地方取消编辑模式的代码
            $(document).on('click', function(e) {
                if (!$(e.target).closest('.actions').length && !$(e.target).closest('.edit').length) {
                    $('.actions').each(function() {
                        const $actions = $(this);
                        if ($actions.find('.cancel-edit').length) {
                            restoreOriginalButtons($actions);
                        }
                    });
                }
            });

            // 修改点击小时的处理代码
            $('.delete-small-icon').on('click', function(e) {
                e.stopPropagation();
                const $icon = $(this);
                const $subCategory = $icon.closest('.sub-category-item');

                if ($icon.closest('.category').hasClass('delete-mode')) {
                    const subCategoryId = $icon.closest('span').data('id');
                    if (confirm('确要删除这个小分类吗？')) {
                        $.ajax({
                            url: 'category',
                            type: 'GET',
                            data: {
                                action: 'deleteSubCategory',
                                subCategoryId: subCategoryId
                            },
                            success: function(response) {
                                location.reload();  // 删除成功后刷新页面
                            },
                            error: function() {
                                alert('删除失败，请重试');
                                location.reload();
                            }
                        });
                    }
                }
            });

            // 点击其他地方时取消删除模式
            $(document).on('click', function(e) {
                if (!$(e.target).closest('.category').length &&
                    !$(e.target).closest('.actions').length) {
                    // 使用统一的取消删除模式函数
                    cancelDeleteMode();
                }
            });

            // 处理小分类点击事件
            $('.sub-category-item span').on('click', function () {
                const subCategoryId = $(this).data('id');
                $.ajax({
                    url: 'category',
                    type: 'GET',
                    data: {
                        action: 'listBySubCategory',
                        subCategoryId: subCategoryId
                    },
                    success: function (data) {
                        // 假设服务器返回的HTML片段，直接更品展示部分
                        $('.products').html(data);
                    },
                    error: function () {
                        alert('无法载商品数据，请重试');
                    }
                });
            });

            // 获取模态框元素
            var modal = document.getElementById("imageModal");
            var span = document.getElementsByClassName("close")[0];
            
            // 点击修改图片按钮
            $('.change-image-btn').click(function(e) {
                e.preventDefault();
                var tvId = $(this).data('tv-id');
                $('#televisionId').val(tvId);
                modal.style.display = "block";
            });
            
            // 点击关闭按钮
            span.onclick = function() {
                modal.style.display = "none";
            }
            
            // 点击模态框外部关闭
            window.onclick = function(event) {
                if (event.target == modal) {
                    modal.style.display = "none";
                }
            }
            
            // 处理图片上传
            $('#updateImageForm').on('submit', function(e) {
                e.preventDefault();
                var formData = new FormData(this);
                
                // 添加调试日志
                console.log('Submitting form with televisionId:', $('#televisionId').val());
                
                $.ajax({
                    url: 'television',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        console.log('Server response:', response); // 添加调试日志
                        if(response.success) {
                            // 更新图片
                            var tvId = $('#televisionId').val();
                            $('[data-tv-id="' + tvId + '"]')
                                .closest('.product')
                                .find('img')
                                .attr('src', 'static/img/电视机/' + response.imageUrl);
                            
                            // 关闭模态框
                            modal.style.display = "none";
                            // 重置表单
                            $('#updateImageForm')[0].reset();
                        } else {
                            alert('更新图片失败：' + response.error);
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('Ajax error:', status, error); // 添加错误日志
                        alert('更新图片失败，请重试');
                    }
                });
            });
       });
    </script>
</head>
<body>
    <%request.getSession().removeAttribute("wrong");%>
    <div class="container">
        <!-- 顶部导航栏 -->
        <div class="top">
            <span class="title">电视机分类与商品展示</span>
            <div class="top-actions">
                <a href="television?action=showAddForm" class="add-product-btn">新增商品</a>
                <div class="information">
                    <img src="static/img/头像/${user.avatar}" id="infor-img" alt="头像">
                    <div class="dropdown-content">
                        <a href="info.jsp" id="view-info">查看信息</a>
                        <a href="index.jsp" id="logout">退出</a>
                    </div>
                </div>
            </div>
        </div>

        <!-- 分类部分 -->
        <div class="categories">
            <%
                List<Category> categories = (List<Category>)request.getAttribute("categories");
                Map<Integer, List<SubCategory>> categorySubcategories =
                    (Map<Integer, List<SubCategory>>)request.getAttribute("categorySubcategories");

                if (categories != null) {
                    for (Category category : categories) {
            %>
            <div class="category">
                <span class="category-name"><%= category.getName() %></span>
                <div class="actions">
                    <a href="#" class="edit" data-id="<%= category.getId() %>">编辑</a> |
                    <a href="#" class="delete" data-category-id="<%= category.getId() %>">删除</a>
                </div>
                <div class="small-category">
                    <%
                        List<SubCategory> subCategories = categorySubcategories.get(category.getId());
                        if (subCategories != null && !subCategories.isEmpty()) {
                            for (SubCategory subCategory : subCategories) {
                    %>
                    <div class="sub-category-item">
                        <span data-id="<%= subCategory.getId() %>">
                            <%= subCategory.getName() %>
                            <i class="delete-small-icon">&times;</i>
                        </span>
                    </div>
                    <%
                            }
                        }
                    %>
                </div>
            </div>
            <%
                    }
                }
            %>
        </div>

        <!-- 品展示部分 -->
        <div class="products">
            <%
                List<Television> televisions = (List<Television>)request.getAttribute("televisions");
                if (televisions != null) {
                    for (Television tv : televisions) {
            %>
            <div class="product" data-category="<%= tv.getSubCategory() != null ? tv.getSubCategory().getName() : "" %>">
                <img src="static/img/电视机/<%= tv.getImageUrl() %>" alt="<%= tv.getName() %>">
                <a href="#" class="change-image-btn" data-tv-id="<%= tv.getId() %>">修改图片</a>
                <h3><%= tv.getName() %></h3>
                <p class="price">￥<%= tv.getPrice() %></p>
                <p>屏幕尺寸：<%= tv.getScreenSize() %></p>
                <p>分辨率：<%= tv.getResolution() %></p>
            </div>
            <%
                    }
                }
            %>
        </div>
    </div>

    <!-- 在body末尾添加模态框 -->
    <div id="imageModal" class="modal">
        <div class="modal-content">
            <span class="close">&times;</span>
            <h2>修改商品图片</h2>
            <form id="updateImageForm" enctype="multipart/form-data">
                <input type="hidden" name="action" value="updateImage">
                <input type="hidden" name="televisionId" id="televisionId">
                <input type="file" name="image" accept="image/*" required>
                <button type="submit">保存</button>
            </form>
        </div>
    </div>
</body>
</html>